/**
 * (C)2012 Exlu Corporation. All rights reserved.
 * 文件名 : com.newtouch.mark.file.StringFileInputStream.java
 * 注意事項   :
 */
package com.newtouch.mark.file;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * @author Mark 
 * @version 1.0.1
 * 2012-12-30
 * StringFileInputStream.java
 */
public class StringFileInputStream {

    private Logger              log = Logger.getLogger(StringFileInputStream.class);
    private BufferedInputStream reader;
    private File                file;

    /**
     * 初始化实例，file默认指定一个文件路径
     * @param file 文件路径
     */
    public StringFileInputStream(File file) {
        try {
            this.file = file;
            reader = new BufferedInputStream(new FileInputStream(file));
        } catch (IOException e) {
            log.fatal("初始化文件错误");
        }

    }

    public StringFileInputStream(String filePath) {
        try {
            this.file = new File(filePath);
            reader = new BufferedInputStream(new FileInputStream(filePath));
        } catch (FileNotFoundException e) {
            log.fatal("初始化文件错误:文件不存在");
        }
    }

    /**
     * 写入字符串内容
     */
    public String reader() {

        try {
            byte[] bytes = new byte[(int) this.file.length()];
            int r = reader.read(bytes);
            if (r != file.length()) {
                throw new IOException("读取文件不正确");
            }
            return new String(bytes);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;

    }

    /**
     * 关闭文件，若没有关闭文件，则之前的文件都没有写入
     */
    public void close() {
        try {
            reader.close();
        } catch (IOException e) {
            log.fatal("关闭文件出错");
        }
    }

}
